import React, { CSSProperties, useEffect, useRef } from "react";
import * as echarts from 'echarts'

export interface ReactEchartsProps {
    style?: CSSProperties;
    option: echarts.EChartsOption;
    height?: CSSProperties['height'];
    theme?: 'dark' | string | object;
}

export const ReactEcharts = (props: ReactEchartsProps) => {
    const { style = {}, height = 200, option, theme = 'default' } = props
    const refEcharts = useRef<HTMLDivElement>()
    const _style = (show: boolean): CSSProperties => ({
        overflow: 'hidden',
        height,
        ...style,
        display: show ? 'block' : 'none'
    })

    useEffect(function () {
        if (option && refEcharts.current) {
            (
                echarts.getInstanceByDom(refEcharts.current) || echarts.init(refEcharts.current, theme)
            ).setOption({
                backgroundColor: 'transparent',
                ...option,
            }, false, true)
        }
    }, [option, refEcharts.current])

    return <>
        <div style={_style(!!option)} ref={refEcharts}></div>
    </>
}

export default ReactEcharts